<?php
defined("_VALID_ACCESS") || die('Direct access forbidden');
class SCTV_SmsCommon extends ModuleCommon{
    public static function menu() {
        return array(__('SCTV') => array(
            '__submenu__' => 1, __('Send SMS') => array()
        ));
    }
    public static function cron(){
        //self::cron2();
        return array('cron1'=>0);
    }
	public static function cron1(){
        $dbconn=pg_connect("host=localhost port=5432 dbname=sms user=postgres password=admin");
        $results=pg_query($dbconn,"select * from in_get('MLD', 4)");
        $results=pg_fetch_all($results);
        if($results != null){
            foreach($results as $key=>$sms){
                $id = $sms['id'];
                $sender = $sms['sender'];
                $msg = $sms['msg'];
                $msg_date = $sms['msg_date'];
                $msg_time = $sms['msg_time'];

                $contacts = Utils_RecordBrowserCommon::get_records('contact', array('|mobile_phone_sms'=>$sender, '|mobile_phone_sms_1'=>$sender));
                if(empty($contacts)){ // Không có trong danh sách nhân viên
                    pg_query_params($dbconn,"select in_update_read_counter($1)",array($id));
                }
                else{
                    $contact = array_shift($contacts);
                    $contact_id = $contact['id'];
                    // Kiem tra so dien thoai co phai la cua nhan vien lap dat khong
                    if(array_key_exists('Technical', $contact['group'])){
                        $results = self::processing_sms($contact_id, $msg_date, $msg);
                        print_r($results);
                        if(array_key_exists('MLD', $results)) $mld = $results['MLD']['ID'];
                        else $mld = '';

                        Utils_RecordBrowserCommon::new_record('SCTV_RequirementSms', array(
                            'in_out'=>1,
                            'requirement'=>$mld,
                            'sms_id'=>$id,
                            'employee'=>$contact['id'],
                            'phone_number'=>$sender,
                            'content'=>$msg,
                            'date'=>$msg_date,
                            'time'=>$msg_date . ' ' . $msg_time
                        ));

                        if($results[0] === false){
                            self::send_out($dbconn, $sender, 'MLD#' . $mld . ': ' . $results[1], 'MLD', $mld, $contact_id);
                        }
                        else{
                            $sms_code = $results['MLD']['SMS_CODE'];
                            if($sms_code == 'NT'){
                                $results = self::valid_and_save_acceptance($msg_date, $msg_time, $contact, $results);
                                print_r($results);
                                if($results[0] === false){
                                    self::send_out($dbconn, $sender, 'MLD#' . $mld . ': ' . $results[1], 'MLD', $mld, $contact_id);
                                }
                                else{
                                    self::send_out($dbconn, $sender, 'MLD#' . $mld . ': nghiem thu thanh cong(' . $results['service']  . ')' , 'MLD', $mld, $contact_id);
                                }
                            }
                            elseif($sms_code == 'TT'){
                                $results = self::valid_and_change_status($msg_date, $msg_time, $contact, $results);
                                print_r($results);
                                if($results[0] === false){
                                    self::send_out($dbconn, $sender, 'MLD#' . $mld . ': ' . $results[1], 'MLD', $mld, $contact_id);
                                }
                                else{
                                    self::send_out($dbconn, $sender, 'MLD#' . $mld . ': da doi trang thai ' . Utils_CommonDataCommon::get_value('SCTV/Requirement/Status/' . $results['TT'], true), 'MLD', $mld, $contact_id);
                                }
                            }
                            elseif($sms_code == 'NGAYHEN'){
                                $results = self::valid_and_change_delivery_date($msg_date, $msg_time, $contact, $results);
                                print_r($results);
                                if($results[0] === false){
                                    self::send_out($dbconn, $sender, 'MLD#' . $mld . ': ' . $results[1], 'MLD', $mld, $contact_id);
                                }
                                else{
                                    self::send_out($dbconn, $sender, 'MLD#' . $mld . ': da thay doi ngay hen ' . date('d/m/Y', strtotime($results['NGAY'])), 'MLD', $mld, $contact_id);
                                }
                            }
                        }
                        echo '<hr>';

                        pg_query_params($dbconn,"select in_update_read_counter($1)",array($id));
                    }
                    else{
                        pg_query_params($dbconn,"select in_update_read_counter($1)",array($id));
                    }
                }
            }
        }
        pg_close($dbconn);
	}

    private static function processing_sms($technical, $msg_date, $msg)
    {
        $result = array();
        $parts = explode(',', $msg);
        $mld = self::parse_mld($parts[0]);
        if($mld === false){
            $result = array(false, 'Sai cu phap MLD');
        }
        else{
            // kiem tra ma lap dat
            $requirement = Utils_RecordBrowserCommon::get_record('SCTV_Requirement', $mld);
            if($requirement == null){
                $result = array(false, 'khong co', 'MLD' => array('ID'=>$mld));
            }
            else{
                $status = $requirement['status'];
                $command_type = self::check_command_type($parts);

                switch($command_type){
                    case 'NT':
                        if($status == 0 || $status == 3){
                            if(self::check_requirement_technical($mld, $technical, $status==0?$msg_date:null))
                                $result = self::parse_nt($parts);
                            else
                                $result = array(false, 'khong duoc giao cho anh');
                        }
                        else{
                            $result = array(false, 'da duoc chot truoc day');
                        }
                        break;
                    case 'TT':
                        if($status == 0){
                            if(self::check_requirement_technical($mld, $technical, $msg_date)){
                                $result = self::parse_tt($parts);
                                $result['MLD'] = array('ID'=>$mld, 'SMS_CODE'=>$command_type, 'STATUS'=>$status);
                            }
                            else{
                                $result = array(false, 'khong duoc giao cho anh');
                            }
                        }
                        else{
                            $result = array(false, 'da duoc chot truoc day');
                        }
                        break;
                    case 'NGAYHEN':
                        if($status == 0){
                            if(self::check_requirement_technical($mld, $technical, $msg_date)){
                                $result = self::parse_ngayhen($parts);
                                $result['MLD'] = array('ID'=>$mld, 'SMS_CODE'=>$command_type, 'STATUS'=>$status);
                            }
                            else{
                                $result = array(false, 'khong duoc giao cho anh');
                            }
                        }
                        else{
                            $result = array(false, 'da duoc chot truoc day');
                        }
                        break;
                    default:
                        $result = array(false, 'khong nhan ra cu phap');
                        break;
                }
                $result['MLD'] = array('ID'=>$mld, 'SMS_CODE'=>$command_type, 'STATUS'=>$status);
            }
        }

        return $result;
    }
    private static function pre_processing($part, $replace_space = true, $upper = true, $beginning_trim = false){
        if($replace_space) $part = str_replace(' ', '', $part);
        if($upper) $part = strtoupper($part);
        if($beginning_trim) $part = ltrim($part);
        return $part;
    }
    private static function parse_mld($mld){
        $mld = self::pre_processing($mld);
        if(preg_match("/^MLD\(([0-9]+)\)$/", $mld, $matches))
        {
            return $matches[1];
        }
        else return false;
    }
    private  static function parse_nt($parts)
    {
        $result = array();

        $ltm = self::parse_thc($parts[1]);
        if($ltm[0] === false){
            $result = $ltm;
        }
        else{
            $net = self::parse_net($parts[2]);
            if($net[0] === false){
                $result = $net;
            }
            else{
                $tg = self::parse_tg($parts[3]);
                if($tg[0] === false){
                    $result = $tg;
                }
                else{
                    $tap = self::parse_tap($parts[4]);
                    if($tap[0] === false){
                        $result = $tap;
                    }
                    else{
                        $tvt = self::parse_tvt($parts[5]);
                        if($tvt[0] === false){
                            $result = $tvt;
                        }
                        else{
                            return array(true, 'THC'=>$ltm, 'NET'=>$net, 'TG'=>$tg, 'TAP'=>$tap, 'TVT'=>$tvt);
                        }
                    }
                }
            }
        }

        return $result;
    }
    private  static function parse_tt($parts)
    {
        $result = array(false);
        $part1 = self::pre_processing($parts[1]);
        if(preg_match("/^TT\(([0-9]+)\)$/", $part1, $matches_tt)){
            $tt = $matches_tt[1];
            if($tt >= 2 && $tt <= 15){
                $part2 = self::pre_processing($parts[2], false, true, true);
                if(preg_match("/^GC\((.+)\)/", $part2, $matches_gc)){
                    $ghichu = $matches_gc[1];
                    if($ghichu == 'X') $ghichu = null;
                    $result = array(true, 'TT'=>$tt, 'GHICHU'=>$ghichu);
                }
                else
                    $result = array(false, 'thieu ghi chu');
            }
            else
                $result = array(false, 'ma trang thai khong dung');
        }
        else{
            $result = array(false, 'sai cu phap TT');
        }

        return $result;
    }
    private  static function parse_ngayhen($parts)
    {
        $result = array(false);
        $part1 = self::pre_processing($parts[1]);

        if(preg_match("/^NGAYHEN\(([0-9]+)\:([0-9]+)\:([0-9]+)\)$/", $part1, $matches)){
            if(checkdate($matches[2], $matches[1], $matches[3])){
                $date = date('Y-m-d', mktime(0,0,0,$matches[2], $matches[1], $matches[3]));
                if($date >= date('Y-m-d'))
                {
                    $part2 = self::pre_processing($parts[2], false, true, true);
                    if(preg_match("/^GC\((.+)\)/", $part2, $matches)){
                        $ghichu = $matches[1];
                        if($ghichu == 'X') $ghichu = null;
                        $result = array(true, 'NGAY'=>$date, 'GHICHU'=>$ghichu);
                    }
                    else
                        $result = array(true, 'NGAY'=>$date);
                }
                else{
                    $result = array(false, 'sai ngay hen');
                }
            }
            else{
                $result = array(false, 'ngay hen khong dung');
            }
        }
        else{
            $result = array(false, 'sai cu phap NGAYHEN');
        }

        return $result;
    }
    private  static function parse_thc($part)
    {
        $result = array(false);
        $part = self::pre_processing($part);
        if(preg_match("/^THC\(([a-zA-Z0-9\:\/]+)\)$/", $part, $matches))
        {
            $thc = $matches[1];
            $children = explode('/', $matches[1]);
            /*if(count($children) == 4){
                if(preg_match("/^NV:([X|M|T]+)$/", $children[0], $matches_nv)){
                    if($matches_nv[1] == 'X'){
                        $result = array(true, 'NV'=>$matches_nv[1]);
                    }
                    else{
                        if(preg_match("/^HD:(X|[0-9]+)$/", $children[1], $matches_hd)){
                            if(preg_match("/^SD:(X|[0-9]+)$/", $children[2], $matches_sd)){
                                if(preg_match("/^SOHD:(X|[0-9]+)$/", $children[3], $matches_sohd)){
                                    $result = array(true, 'NV'=>$matches_nv[1], 'HD'=>$matches_hd[1], 'SD'=>$matches_sd[1], 'SOHD'=>$matches_sohd[1]);
                                }
                                else{
                                    $result = array(false, 'sai cu phap SOHD cua THC');
                                }
                            }
                            else{
                                $result = array(false, 'sai cu phap SD cua THC');
                            }
                        }
                        else{
                            $result = array(false, 'sai cu phap HD cua THC');
                        }
                    }
                }
                else{
                    $result = array(false, 'sai nghiep vu cua THC');
                }
            }
            else{
                $result = array(false, 'thieu noi dung THC');
            }*/

            if(count($children) == 6){
                if(preg_match("/^NV:([X|M|T]+)$/", $children[0], $matches_nv)){
                    if($matches_nv[1] == 'X'){
                        $result = array(true, 'NV'=>$matches_nv[1]);
                    }
                    else{
                        if(preg_match("/^HD:(X|[0-9]+)$/", $children[1], $matches_hd)){
                            if(preg_match("/^SD:(X|[0-9]+)$/", $children[2], $matches_sd)){
                                if(preg_match("/^MAL:(X|[0-9]+)$/", $children[3], $matches_mal)){
                                    if(preg_match("/^SAL:(X|[0-9]+)$/", $children[4], $matches_sal)){
                                        if(preg_match("/^SOHD:(X|[0-9]+)$/", $children[5], $matches_sohd)){
                                            $result = array(true, 'NV'=>$matches_nv[1], 'HD'=>$matches_hd[1], 'SD'=>$matches_sd[1], 'MAL'=>$matches_mal[1], 'SAL'=>$matches_sal[1], 'SOHD'=>$matches_sohd[1]);
                                        }
                                        else{
                                            $result = array(false, 'sai cu phap SOHD cua THC');
                                        }
                                    }
                                    else{
                                        $result = array(false, 'sai cu phap SAL cua THC');
                                    }
                                }
                                else{
                                    $result = array(false, 'sai cu phap MAL cua THC');
                                }
                            }
                            else{
                                $result = array(false, 'sai cu phap SD cua THC');
                            }
                        }
                        else{
                            $result = array(false, 'sai cu phap HD cua THC');
                        }
                    }
                }
                else{
                    $result = array(false, 'sai nghiep vu cua THC');
                }
            }
            else{
                $result = array(false, 'thieu noi dung THC');
            }

        }
        else{
            $result = array(false, 'sai cu phap THC');
        }

        return $result;
    }
    private static function parse_net($part)
    {
        $result = array(false);
        $part = self::pre_processing($part);
        if(preg_match("/^NET\(([a-zA-Z0-9\:\/]+)\)$/", $part, $matches)){
            $children = explode('/', $matches[1]);
            if(count($children) == 3){
                if(preg_match("/^GOI:(X|2|4|10)$/", $children[0], $matches_package)){
                    if($matches_package[0] == 'X'){
                        $result = array(true, 'GOI'=>$matches_package[1]);
                    }
                    else{
                        if(preg_match("/^WF:(X|1)$/", $children[1], $matches_wf)){
                            if(preg_match("/^SOHD:(X|[0-9]+)$/", $children[2], $matches_sohd)){
                                $result = array(true, 'GOI'=>$matches_package[1], 'WF'=>$matches_wf[1], 'SOHD'=>$matches_sohd[1]);
                            }
                            else{
                                $result = array(false, 'sai so hop dong NET');
                            }
                        }
                        else{
                            $result = array(false, 'sai muon wifi cua NET');
                        }
                    }
                }
                else{
                    $result = array(false, 'sai goi NET');
                }
            }
            else{
                $result = array(false, 'sai noi dung NET');
            }
        }
        else{
            $result = array(false, 'sai cu phap NET');
        }

        return $result;
    }
    private static function parse_tg($part){
        $result = array(false);
        $part = self::pre_processing($part);
        if(preg_match("/^TG\((X|BE|B|GE|G|D)\)$/", $part, $matches)){
            $result = array(true, 'TG'=>$matches[1]);
        }
        else{
            $result = array(false, 'Sai cu phap TG');
        }

        return $result;
    }
    private static function parse_tap($part){
        $result = array(false);
        $part = self::pre_processing($part);
        if(preg_match("/^TAP\(([a-zA-Z0-9\:\/]+)\)$/", $part, $matches)){
            $children = explode('/', $matches[1]);
            if(count($children) == 2){
                if(preg_match("/^MA:(X|[0-9]+)$/", $children[0], $matches_ma)){
                    if(preg_match("/^PORT:(X|[0-9]+)$/", $children[1], $matches_port)){
                        $result = array(true, 'MA'=>$matches_ma[1], 'PORT'=>$matches_port[1]);
                    }
                    else{
                        $result = array(false, 'sai ma PORT');
                    }
                }
                else{
                    $result = array(false, 'sai ma TAP');
                }
            }
            else{
                $result = array(false, 'sai noi dung TAP');
            }
        }
        else{
            $result = array(false, 'sai cu phap TAP');
        }

        return $result;
    }
    private  static function parse_tvt($part)
    {
        $result = array(false);
        $part = self::pre_processing($part);
        if(preg_match("/^TVT\(([a-zA-Z0-9\:\/]+)\)$/", $part, $matches)){
            $children = explode('/', $matches[1]);
            /*if(count($children) == 4){
                if(preg_match("/^MNV:(X|[0-9][0-9][0-9])$/", $children[0], $matches_mnv)){
                    if($matches_mnv[1] == 'X'){
                        $result = array(true, 'MNV'=>$matches_mnv[1]);
                    }
                    else{
                        if(preg_match("/^HD:(X|[0-9]+)$/", $children[1], $matches_hd)){
                            if(preg_match("/^SD:(X|[0-9]+)$/", $children[2], $matches_sd)){
                                if(preg_match("/^NET:(X|1)$/", $children[3], $matches_net)){
                                    $result = array(true, 'MNV'=>$matches_mnv[1], 'HD'=>$matches_hd[1], 'SD'=>$matches_sd[1], 'NET'=>$matches_net[1]);
                                }
                                else{
                                    $result = array(false, 'sai cu phap NET cua TVT');
                                }
                            }
                            else{
                                $result = array(false, 'sai cu phap SD cua TVT');
                            }
                        }
                        else{
                            $result = array(false, 'sai cu phap HD cua TVT');
                        }
                    }
                }
                else{
                    $result = array(false, 'sai ma nhan vien cua TVT');
                }
            }
            else{
                $result = array(false, 'sai noi dung TVT');
            }*/
            if(count($children) == 6){
                if(preg_match("/^MNV:(X|[0-9][0-9][0-9])$/", $children[0], $matches_mnv)){
                    if($matches_mnv[1] == 'X'){
                        $result = array(true, 'MNV'=>$matches_mnv[1]);
                    }
                    else{
                        if(preg_match("/^HD:(X|[0-9]+)$/", $children[1], $matches_hd)){
                            if(preg_match("/^SD:(X|[0-9]+)$/", $children[2], $matches_sd)){
                                if(preg_match("/^MAL:(X|[0-9]+)$/", $children[3], $matches_mal)) {
                                    if(preg_match("/^SAL:(X|[0-9]+)$/", $children[4], $matches_sal)) {
                                        if(preg_match("/^NET:(X|1)$/", $children[5], $matches_net)){
                                            $result = array(true, 'MNV'=>$matches_mnv[1], 'HD'=>$matches_hd[1], 'SD'=>$matches_sd[1], 'MAL'=>$matches_mal[1], 'SAL'=>$matches_sal[1], 'NET'=>$matches_net[1]);
                                        }
                                        else{
                                            $result = array(false, 'sai cu phap NET cua TVT');
                                        }
                                    } else {
                                        $result = array(false, 'sai cu phap SAL cua TVT');
                                    }
                                } else {
                                    $result = array(false, 'sai cu phap MAL cua TVT');
                                }
                            }
                            else{
                                $result = array(false, 'sai cu phap SD cua TVT');
                            }
                        }
                        else{
                            $result = array(false, 'sai cu phap HD cua TVT');
                        }
                    }
                }
                else{
                    $result = array(false, 'sai ma nhan vien cua TVT');
                }
            }
            else{
                $result = array(false, 'sai noi dung TVT');
            }
        }
        else{
            $result = array(false, 'sai cu phap TVT');
        }

        return $result;
    }
    private static function check_requirement_technical($requirement, $technical, $date){
        if($date == null){ // Kiem tra khong theo ngay, lay record cuoi cung
            $records = Utils_RecordBrowserCommon::get_records('SCTV_Deployment', array('requirement'=>$requirement), array(), array('date'=>'desc'), 1);
            if(empty($records))
                return false;
            else{
                $record = array_shift($records);
                if($record['technical'] == $technical){
                    return true;
                }
                else
                    return false;
            }
        }
        else{ // Kiem tra theo ngay
            $records = Utils_RecordBrowserCommon::get_records('SCTV_Deployment', array('requirement'=>$requirement, 'technical'=>$technical, 'date'=>$date));
            if(empty($records))
                return false;
            else
                return true;
        }
    }
    private static function check_command_type($parts)
    {
        $result = null;

        $parts_count = count($parts);
        $part1 = self::pre_processing($parts[1]);

        if($parts_count == 6 && strpos($part1, 'THC') === 0){
            $result = 'NT';
        }
        elseif($parts_count >= 2){
            if(strpos($part1, 'TT') === 0){
                $result = 'TT';
            }
            elseif(strpos($part1, 'NGAYHEN') === 0){
                $result = 'NGAYHEN';
            }
        }

        return $result;
    }
	private static function valid_and_save_acceptance($msg_date, $msg_time, $contact, $results)
    {
		$thc = $results['THC'];
		$deployment_cable_status = $thc['NV'];
        if($deployment_cable_status == 'X'){
			$deployment_cable_status = null;
			$deploymenthd = 0;
			$deploymentsd = 0;
            $deployment_main_analog = 0;
            $deployment_sub_analog = 0;
			$cablecontractcode = null;
		}
		else{
			$deployment_cable_status = ($deployment_cable_status == 'M'?'1':'0');
			$deploymenthd = $thc['HD'];
			$deploymenthd = $deploymenthd == 'X'?0:$deploymenthd;
			$deploymentsd = $thc['SD'];
			$deploymentsd = $deploymentsd == 'X'?0:$deploymentsd;
            $deployment_main_analog = $thc['MAL'];
            $deployment_main_analog = $deployment_main_analog == 'X' ? 0 : $deployment_main_analog;
            $deployment_sub_analog = $thc['SAL'];
            $deployment_sub_analog = $deployment_sub_analog == 'X' ? 0 : $deployment_sub_analog;
            $cablecontractcode = $thc['SOHD'];

            if ( $deployment_cable_status == 1 ) // lắp mới
            {
                if($deploymenthd <= 0 && $deploymentsd <= 0 && $deployment_main_analog <= 0 && $deployment_sub_analog <= 0 ){
                    return array(false, 'sai so luong HD/SD/MAL/SAL');
                }
                elseif( ($deploymenthd > 0 || $deploymentsd > 0) && $deployment_main_analog <= 0 ) {
                    return array(false, 'nhap thieu main analog');
                }
                elseif($cablecontractcode == 'X'){
                    return array(false, 'thieu hop dong THC');
                }
            }
		}
		
		$net = $results['NET'];
		$deploymentinternetpackage = $net['GOI'];
		if($deploymentinternetpackage == 'X'){
			$deploymentinternetpackage = null;
			$internetcontractcode = null;

            if($deployment_cable_status == null){
                return array(false, 'thieu nghiep vu THC hoac goi NET');
            }
		}
		else{
			$internetcontractcode = $net['SOHD'];
			$lend_wifi = $net['WF'];
			if($internetcontractcode == 'X'){
				return array(false, 'thieu hop dong NET');
			}
			elseif(
                    (
                        $deploymentinternetpackage == 'PL' ||
                        $deploymentinternetpackage == 'PR' ||
                        $deploymentinternetpackage == 'H' ||
                        $deploymentinternetpackage == 'E'
                    ) &&
                    $deployment_cable_status != null)
            {
				return array(false, 'sai goi NET');
			}
			elseif($lend_wifi == 'X'){
                $lend_wifi = 0;
			}
		}
		
		$deploymentbundle = $results['TG']['TG'];
		if($deploymentbundle == 'X'){
			if(
                $deploymentinternetpackage == '2' ||
                $deploymentinternetpackage == '4' ||
                $deploymentinternetpackage == '10'
            )
				return array(false, 'thieu goi tron goi');
			else{
			}
		}
		elseif(
                $deploymentinternetpackage == 'E' ||
                $deploymentinternetpackage == 'H' ||
                $deploymentinternetpackage == 'PL' ||
                $deploymentinternetpackage == 'PR'
        ){
			return array(false, 'sai goi NET va tron goi');
		}
        elseif($deployment_cable_status == 1){ // lắp mới
            if($deploymenthd > 0 && $deployment_main_analog > 0){
                if($deploymenthd >= 3) {
                    if ( $deploymentinternetpackage == '10' && $deploymentbundle != 'D' ) {
                        return array(false, 'sai thong tin tron goi');
                    }
                }

                if(
                    $deploymentinternetpackage == '2' &&
                    $deploymentbundle != 'GE'
                ){
                    return array(false, 'sai thong tin tron goi');
                }
                elseif(
                    $deploymentinternetpackage == '4' &&
                    $deploymentbundle != 'G'
                ){
                    return array(false, 'sai thong tin tron goi');
                }
            }
            elseif($deployment_main_analog > 0){
                if(
                    $deploymentinternetpackage == '2' &&
                    $deploymentbundle != 'BE'
                ){
                    return array(false, 'sai thong tin tron goi');
                }
                elseif(
                    $deploymentinternetpackage == '4' &&
                    $deploymentbundle != 'B'
                ){
                    return array(false, 'sai thong tin tron goi');
                }
            }else{
                return array(false, 'nhap thieu main analog');
            }
        }
        elseif($deployment_cable_status == 0){ // lắp thêm
        }

        $tap = $results['TAP'];
        $tapcode = $tap['MA'];
        $port = $tap['PORT'];
        if($tapcode == 'X'){
            if($port == 'X'){
                $tapcode = null;
            }
            else{
                $tapcode = $port;
            }
        }
        else{
            if($port == 'X'){
                $tapcode = $tapcode;
            }
            else{
                $tapcode = $tapcode . '/' . $port;
            }
        }

        $tvt = $results['TVT'];
        $secondary_counselor = $tvt['MNV'];
        if($secondary_counselor == 'X'){
            $secondary_counselor = null;
            $secondary_hd = 0;
            $secondary_sd = 0;
            $secondary_main_analog = 0;
            $secondary_sub_analog = 0;
            $secondary_internetpackage = null;
        }
        else{
            $secondary_counselor_contacts = Utils_RecordBrowserCommon::get_records('contact', array('employee_code'=>'QNH-' . $secondary_counselor));
            if(empty($secondary_counselor_contacts)){ // Không có trong danh sách nhân viên
                return array(false, 'ma nhan vien tvt khong co');
            }
            else{
                $secondary_counselor = array_shift($secondary_counselor_contacts);

                $secondary_counselor = $secondary_counselor['id'];

                $secondary_hd = $tvt['HD'];
                $secondary_hd = $secondary_hd == 'X'?0:$secondary_hd;
                $secondary_sd = $tvt['SD'];
                $secondary_sd = $secondary_sd == 'X'?0:$secondary_sd;
                $secondary_main_analog = $tvt['MAL'];
                $secondary_main_analog = $secondary_main_analog == 'X' ? 0 : $secondary_main_analog;
                $secondary_sub_analog = $tvt['SAL'];
                $secondary_sub_analog = $secondary_sub_analog == 'X' ? 0 : $secondary_sub_analog;
                $secondary_internetpackage = $tvt['NET'];

                if($secondary_hd <= 0 && $secondary_sd <= 0 && $secondary_main_analog <= 0 && $secondary_sub_analog <= 0 && $secondary_internetpackage == 'X'){
                    return array(false, 'thieu dich vu cua TVT');
                }

                if(
                    $deploymenthd >= $secondary_hd &&
                    $deploymentsd >= $secondary_sd &&
                    ($deploymenthd + $deploymentsd) >= ($secondary_hd + $secondary_sd)
                )
                {
                }
                else{
                    return array(false, 'sai so HD hoac SD cua TVT');
                }

                if(
                    $deployment_main_analog >= $secondary_main_analog &&
                    $deployment_sub_analog >= $secondary_sub_analog &&
                    ($deployment_main_analog + $deployment_sub_analog) >= ($secondary_main_analog + $secondary_sub_analog)
                )
                {
                }
                else{
                    return array(false, 'sai so MAL hoac SAL cua TVT');
                }

                if($deploymentinternetpackage == null && $secondary_internetpackage == '1'){
                    return array(false, 'sai NET cua TVT');
                }
            }
        }

        switch($deploymentinternetpackage)
        {
            case '2': $deploymentinternetpackage = 1;break;
            case '4': $deploymentinternetpackage = 2;break;
            case '10': $deploymentinternetpackage = 3;break;
            case 'E': $deploymentinternetpackage = 4;break;
            case 'H': $deploymentinternetpackage = 5;break;
            case 'PR': $deploymentinternetpackage = 6;break;
            case 'PL': $deploymentinternetpackage = 7;break;
        }

        if($secondary_internetpackage == '1') $secondary_internetpackage = $deploymentinternetpackage;
        else $secondary_internetpackage = null;

        switch($deploymentbundle)
        {
            case 'BE': $deploymentbundle = 2;break;
            case 'B': $deploymentbundle = 1;break;
            case 'GE': $deploymentbundle = 4;break;
            case 'G': $deploymentbundle = 3;break;
            case 'D': $deploymentbundle = 5;break;
            default: $deploymentbundle = null;break;
        }

        if($deploymentbundle == null) $deployment_bundle_text = '';
        else $deployment_bundle_text = Utils_RecordBrowserCommon::get_value('SCTV_Bundle', $deploymentbundle, 'name');

        $mld = $results['MLD'];

        $deployment_business = SCTV_RequirementCommon::create_business($deployment_cable_status, $deploymentinternetpackage, $deploymentbundle, $deployment_bundle_text);


        $bundlecontractcode = '';
        if($mld['STATUS'] == 3){// Da cho trang thai
            Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $mld['ID'],
                array(
                    'status'=>1,
                    'acceptance_date'=>$msg_date,
                    'deployment_cable_status'=>$deployment_cable_status,
                    'deployment_employee'=>$contact['id'],
                    'deployment_main_analog'=>$deployment_main_analog,
                    'deployment_sub_analog'=>$deployment_sub_analog,
                    'deployment_hd'=>$deploymenthd,
                    'deployment_sd'=>$deploymentsd,
                    'deployment_internet_package'=>$deploymentinternetpackage,
                    'deployment_bundle'=>$deploymentbundle,
                    'deployment_business'=>$deployment_business,
                    'cable_contract_code'=>$cablecontractcode,
                    'internet_contract_code'=>$internetcontractcode,
                    'bundle_contract_code'=>$bundlecontractcode,
                    'tap_code'=>$tapcode,
                    'lend_wifi'=>$lend_wifi,
                    'secondary_counselor'=>$secondary_counselor,
                    'secondary_main_analog'=>$secondary_main_analog,
                    'secondary_sub_analog'=>$secondary_sub_analog,
                    'secondary_hd'=>$secondary_hd,
                    'secondary_sd'=>$secondary_sd,
                    'secondary_internet_package'=>$secondary_internetpackage
                )
            );

            $service = '';
            if($deploymenthd > 0) $service .= $deploymenthd . 'HD ';
            if($deploymentsd > 0) $service .= $deploymentsd . 'SD ';
            if($deployment_main_analog > 0) $service .= $deployment_main_analog . 'MAL ';
            if($deployment_sub_analog > 0) $service .= $deployment_sub_analog . 'SAL ';
            if(!empty($deploymentinternetpackage)){
                $service .= 'NET:' . Utils_RecordBrowserCommon::get_value('SCTV_InternetPackage', $deploymentinternetpackage, 'name') . ' ';
                $service .= 'Wifi:' . $lend_wifi;
            }

            $results = array(true, 'service'=>$service);
        }
        else{
            Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $mld['ID'],
                array(
                    'status'=>1,
                    'deployment_date'=>$msg_date,
                    'deployment_time'=>$msg_date . ' ' . $msg_time,
                    'acceptance_date'=>$msg_date,
                    'deployment_cable_status'=>$deployment_cable_status,
                    'deployment_employee'=>$contact['id'],
                    'deployment_main_analog'=>$deployment_main_analog,
                    'deployment_sub_analog'=>$deployment_sub_analog,
                    'deployment_hd'=>$deploymenthd,
                    'deployment_sd'=>$deploymentsd,
                    'deployment_internet_package'=>$deploymentinternetpackage,
                    'deployment_bundle'=>$deploymentbundle,
                    'deployment_business'=>$deployment_business,
                    'cable_contract_code'=>$cablecontractcode,
                    'internet_contract_code'=>$internetcontractcode,
                    'bundle_contract_code'=>$bundlecontractcode,
                    'tap_code'=>$tapcode,
                    'lend_wifi'=>$lend_wifi,
                    'secondary_counselor'=>$secondary_counselor,
                    'secondary_main_analog'=>$secondary_main_analog,
                    'secondary_sub_analog'=>$secondary_sub_analog,
                    'secondary_hd'=>$secondary_hd,
                    'secondary_sd'=>$secondary_sd,
                    'secondary_internet_package'=>$secondary_internetpackage
                )
            );

            $service = '';
            if($deploymenthd > 0) $service .= $deploymenthd . 'HD ';
            if($deploymentsd > 0) $service .= $deploymentsd . 'SD ';
            if($deployment_main_analog > 0) $service .= $deployment_main_analog . 'MAL ';
            if($deployment_sub_analog > 0) $service .= $deployment_sub_analog . 'SAL ';
            if(!empty($deploymentinternetpackage)){
                $service .= 'NET:' . Utils_RecordBrowserCommon::get_value('SCTV_InternetPackage', $deploymentinternetpackage, 'name') . ' ';
                $service .= 'Wifi:' . $lend_wifi;
            }

            $results = array(true, 'service'=>$service);
        }

        return $results;
    }
    private static function valid_and_change_status($msg_date, $msg_time, $contact, $results){
		$status = $results['TT'];
		$mld = $results['MLD'];
		if($status == 3){
			Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $mld['ID'],
                array(
                    'status'=>$status,
					'deployment_date'=>$msg_date,
                    'deployment_time'=>$msg_date . ' ' . $msg_time
				));
		}
		else{
		    Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $mld['ID'],
                array(
                    'status'=>$status
				));
		}

        Utils_RecordBrowserCommon::update_record('SCTV_StatusHistory', $mld['ID'],
            array(
                'requirement'=>$mld['ID'],
                'date_time'=>$msg_date . ' ' . $msg_time,
                'employee'=>$contact['id'],
                'status'=>$status,
                'note'=>$results['GHICHU']
            )
        );

		return $results;
    }
    private static function valid_and_change_delivery_date($msg_date, $msg_time, $contact, $results){
        $mld = $results['MLD'];
        Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $mld['ID'],
            array(
                'delivery_date'=>$results['NGAY']
           )
        );

        Utils_RecordBrowserCommon::new_record('SCTV_DeliveryDateHistory', array(
            'requirement'=>$mld['ID'],
            'date_time'=>$msg_date . ' ' . $msg_time,
            'employee'=>$contact['id'],
            'delivery_date'=>$results['NGAY'],
            'note'=>$results['GHICHU']
        ));

        return $results;
    }
    public static function send_out($db, $receiver, $content, $code, $requirement = null, $employee = null){
        if(mb_strlen($content) > 160){
            $content1 = mb_substr($content, 0, 160);
            $content2 = mb_substr($content, 160);
            if(!empty($content1)) self::send_out($db, $receiver, $content1, $code, $requirement, $employee);
            if(!empty($content2)) self::send_out($db, $receiver, $content2, $code, $requirement, $employee);
        }
        else{
            $result = pg_query_params($db,"select * from out_insert($1, $2, $3)",array($receiver, $content, $code));

            $results=pg_fetch_all($result);
            $row = array_shift($results);


            if($requirement == null){
                Utils_RecordBrowserCommon::new_record('SCTV_Sms', array(
                    'sms_id'=>$row['id'],
                    'receiver'=>$employee,
                    'content'=>$content,
                    'date'=>$row['request_date'],
                    'time'=>$row['request_date'] . ' ' . $row['request_time']
                ));
            }
            else{
                Utils_RecordBrowserCommon::new_record('SCTV_RequirementSms', array(
                    'in_out'=>0,
                    'requirement'=>$requirement,
                    'sms_id'=>$row['id'],
                    'employee'=>$employee,
                    'phone_number'=>$receiver,
                    'content'=>$content,
                    'date'=>$row['request_date'],
                    'time'=>$row['request_date'] . ' ' . $row['request_time']
                ));
            }
        }
    }
    public static function display_in_out($record, $nolink, $desc){
        return $record[$desc['id']] == 1?'Nhận':'Gửi';
    }
    public static function send_sms(){
        $dbconn=pg_connect("host=localhost port=5432 dbname=sms user=postgres password=admin");

        $ret = DB::Execute("SELECT * FROM sctv_requirement_notify WHERE sms_sent = 'f' ORDER BY date_time asc LIMIT 4");
        while ($row = $ret->FetchRow()) {
            $requirement = $row['requirement'];
            $date_time = $row['date_time'];
            $action = $row['action'];
            $old_value = $row['old_value'];
            $new_value = $row['new_value'];

            // lay thong tin lap dat
            $requirement = Utils_RecordBrowserCommon::get_record('SCTV_Requirement', $requirement);

            $counselor = $requirement['counselor'];
            $counselor = Utils_RecordBrowserCommon::get_record('contact', $counselor);

            if($new_value == 0){
                if(empty($counselor['mobifone'])){
                }
                else{
                    $msg = 'Thong bao da dang ky yeu cau: ' . self::requirement_to_text($requirement, true);
                    self::send_out($dbconn, $counselor['mobifone'], $msg, 'TT', $requirement['id'], $counselor['id']);
                }
            }
            elseif($new_value == 1){ // Nghiem thu
                $secondary_counselor = $requirement['secondary_counselor'];
                $secondary_counselor = Utils_RecordBrowserCommon::get_record('contact', $secondary_counselor);

                if(empty($counselor['mobifone'])){
                    if(!empty($secondary_counselor) && !empty($secondary_counselor['mobifone'])){
                        $msg = 'Thong bao nghiem thu tu van them(' . self::secondary_to_text($requirement) . ')';
                        $msg .= '. ' . self::requirement_to_text($requirement, false);
                        self::send_out($dbconn, $secondary_counselor['mobifone'], $msg, 'TT', $requirement['id'], $secondary_counselor['id']);
                    }
                }
                else{
                    if(empty($secondary_counselor)){
                        // Chi gui cho nhan vien tu van
                        $msg = 'Thong bao da nghiem thu(' . self::acceptance_to_text($requirement) . ')';
                        $msg .= '. ' . self::requirement_to_text($requirement, true);
                        self::send_out($dbconn, $counselor['mobifone'], $msg, 'TT', $requirement['id'], $counselor['id']);
                    }
                    else{
                        // Tinh so hd, sd, net, de gui cho nhan vien tu van va tu van them
                        $msg = 'Thong bao da nghiem thu(' . self::acceptance_to_text($requirement, true) . ')';
                        $msg .= '. ' . self::requirement_to_text($requirement, true);
                        self::send_out($dbconn, $counselor['mobifone'], $msg, 'TT', $requirement['id'], $counselor['id']);

                        if(!empty($secondary_counselor['mobifone'])){
                            $msg = 'Thong bao nghiem thu tu van them(' . self::secondary_to_text($requirement) . ')';
                            $msg .= '. ' . self::requirement_to_text($requirement, false);
                            self::send_out($dbconn, $secondary_counselor['mobifone'], $msg, 'TT', $requirement['id'], $secondary_counselor['id']);
                        }
                    }
                }
            }
            else{
                if(empty($counselor['mobifone'])){
                }
                else{
                    $msg = 'Thong bao da chuyen sang trang thai ' . Utils_CommonDataCommon::get_value('SCTV/Requirement/Status/' . $new_value, true);
                    $msg .= '. ' . self::requirement_to_text($requirement, true);
                    self::send_out($dbconn, $counselor['mobifone'], $msg, 'TT', $requirement['id'], $counselor['id']);
                }
            }

            DB::Execute("update sctv_requirement_notify SET sms_sent = 't' where requirement = %d and date_time = %T", array($requirement['id'], $date_time));
        }
    }
    private function requirement_to_text($requirement, $with_requirement_service = false){
        $result = 'KH#' . $requirement['id'];

        $customer_name = $requirement['customer_name'];
        if(!empty($customer_name)) $result = $result . ' ' . $customer_name;

        $result = $result . ' DC: ' . $requirement['address'] . ' ' . Utils_RecordBrowserCommon::get_value('SCTV_Street', $requirement['street'], 'name');

        $result = $result . ' DT: ' . $requirement['phone'];

        $service = '';
        if($with_requirement_service){
            $cable_status = $requirement['cable_status'];
            if($cable_status != null){
                $number_of_hd = $requirement['number_of_hd'];
                $number_of_sd = $requirement['number_of_sd'];
                $main_analog = $requirement['main_analog'];
                $sub_analog = $requirement['sub_analog'];
                $service = $cable_status == 1?'Lap moi:':'Lap them:';
                if($number_of_hd > 0) $service = $service . ' ' . $number_of_hd . 'HD';
                if($number_of_sd > 0) $service = $service . ' ' . $number_of_sd . 'SD';
                if($main_analog > 0) $service = $service . ' ' . $main_analog . 'MAL';
                if($sub_analog > 0) $service = $service . ' ' . $sub_analog . 'SAL';
            }

            $internet_package = $requirement['internet_package'];
            if($internet_package != null){
                $internet_package = 'NET: ' . Utils_RecordBrowserCommon::get_value('SCTV_InternetPackage', $internet_package, 'name');
                if(empty($service))
                    $service = $internet_package;
                else
                    $service = $service . ' ' . $internet_package;
            }

            if(!empty($service)) $result = $result . '(' . $service . ')';
        }

        return $result;
    }
    private function acceptance_to_text($requirement, $exclude_secondary = false){
        $service = '';

        $cable_status = $requirement['deployment_cable_status'];
        if($cable_status != null){
            $number_of_hd = $requirement['deployment_hd'];
            $number_of_sd = $requirement['deployment_sd'];
            $main_analog = $requirement['main_analog'];
            $sub_analog = $requirement['sub_analog'];
            $secondary_hd = $requirement['secondary_hd'];
            $secondary_sd = $requirement['secondary_sd'];
            $secondary_main_analog = $requirement['secondary_main_analog'];
            $secondary_sub_analog = $requirement['secondary_sub_analog'];

            if($exclude_secondary){
                $number_of_hd = $number_of_hd - $secondary_hd;
                $number_of_sd = $number_of_sd - $secondary_sd;
                $main_analog = $main_analog - $secondary_main_analog;
                $sub_analog = $sub_analog - $secondary_sub_analog;
            }

            $service = $cable_status == 1?'Lap moi:':'Lap them:';
            if($number_of_hd > 0) $service = $service . ' ' . $number_of_hd . 'HD';
            if($number_of_sd > 0) $service = $service . ' ' . $number_of_sd . 'SD';
            if($main_analog > 0) $service = $service . ' ' . $main_analog . 'MAL';
            if($sub_analog > 0) $service = $service . ' ' . $sub_analog . 'SAL';
        }

        $internet_package = $requirement['deployment_internet_package'];
        if($internet_package != null){
            if($exclude_secondary){
                $secondary_internet_package = $requirement['secondary_internet_package'];
            }
            if(empty($secondary_internet_package)){
                $internet_package = 'NET: ' . Utils_RecordBrowserCommon::get_value('SCTV_InternetPackage', $internet_package, 'name');

                if(empty($service))
                    $service = $internet_package;
                else
                    $service = $service . ' ' . $internet_package;
            }
        }

        return $service;
    }
    private function secondary_to_text($requirement){
        $service = '';

        $cable_status = $requirement['deployment_cable_status'];
        if($cable_status != null){
            $secondary_hd = $requirement['secondary_hd'];
            $secondary_sd = $requirement['secondary_sd'];
            $secondary_main_analog = $requirement['main_analog'];
            $secondary_sub_analog = $requirement['sub_analog'];

            $service = $cable_status == 1?'Lap moi:':'Lap them:';
            if($secondary_hd > 0) $service = $service . ' ' . $secondary_hd . 'HD';
            if($secondary_sd > 0) $service = $service . ' ' . $secondary_sd . 'SD';
            if($secondary_main_analog > 0) $service = $service . ' ' . $secondary_main_analog . 'MAL';
            if($secondary_sub_analog > 0) $service = $service . ' ' . $secondary_sub_analog . 'SAL';
        }

        $internet_package = $requirement['secondary_internet_package'];
        if($internet_package != null){
            $internet_package = 'NET: ' . Utils_RecordBrowserCommon::get_value('SCTV_InternetPackage', $internet_package, 'name');
            if(empty($service))
                $service = $internet_package;
            else
                $service = $service . ' ' . $internet_package;
        }

        return $service;
    }
}
?>